/**
 * Copyright © 2016-2023 The Thingsboard Authors
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.thingsboard.server.dao.util;

import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
import org.thingsboard.server.common.data.kv.KvEntry;
import org.thingsboard.server.dao.exception.DataValidationException;
import org.thingsboard.server.dao.exception.IncorrectParameterException;
import org.thingsboard.server.dao.service.NoXssValidator;

import java.util.List;
import java.util.concurrent.TimeUnit;

public class KvUtils {

    private static final Cache<String, Boolean> validatedKeys;

    static {
        validatedKeys = Caffeine.newBuilder()
                .weakKeys()
                .expireAfterAccess(24, TimeUnit.HOURS)
                .maximumSize(100000).build();
    }

    public static void validate(List<? extends KvEntry> tsKvEntries) {
        tsKvEntries.forEach(KvUtils::validate);
    }

    public static void validate(KvEntry tsKvEntry) {
        if (tsKvEntry == null) {
            throw new IncorrectParameterException("Key value entry can't be null");
        }

        String key = tsKvEntry.getKey();

        if (key == null) {
            throw new DataValidationException("Key can't be null");
        }

        if (key.length() > 255) {
            throw new DataValidationException("Validation error: key length must be equal or less than 255");
        }

        if (validatedKeys.getIfPresent(key) != null) {
            return;
        }

        if (!NoXssValidator.isValid(key)) {
            throw new DataValidationException("Validation error: key is malformed");
        }

        validatedKeys.put(key, Boolean.TRUE);
    }
}
